package com.example.demo.service.impl;

import com.example.demo.dto.NewTaskDTO;
import com.example.demo.dto.NewTaskFlowDTO;
import com.example.demo.dto.ProcessNodeDTO;
import com.example.demo.entity.NewTaskFlow;
import com.example.demo.entity.TaskApprovalStatus;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.NewTaskFlowMapper;
import com.example.demo.mapper.TaskApprovalStatusMapper;
import com.example.demo.request.CreateNewTaskFlowRequest;
import com.example.demo.service.NewTaskFlowService;
import com.example.demo.service.NewTaskService;
import com.example.demo.service.ProcessNodeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NewTaskFlowServiceImpl implements NewTaskFlowService {

    //private static final logger log = loggerFactory.getlogger(NewTaskFlowServiceImpl.class);

    @Autowired
    private NewTaskFlowMapper newTaskFlowMapper;
    
    @Autowired
    private NewTaskService newTaskService;
    
    @Autowired
    private ProcessNodeService processNodeService;
    
    @Autowired
    private TaskApprovalStatusMapper taskApprovalStatusMapper;

    @Override
    public List<NewTaskFlowDTO> getNewTaskFlows(int page, int size, Long taskId, Long flowId) {
        int offset = page * size;
        List<NewTaskFlow> newTaskFlows = newTaskFlowMapper.selectPage(offset, size, taskId, flowId);
        return newTaskFlows.stream()
                .map(NewTaskFlowDTO::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    public long countNewTaskFlows(Long taskId, Long flowId) {
        return newTaskFlowMapper.count(taskId, flowId);
    }

    @Override
    public NewTaskFlowDTO getNewTaskFlowById(Long id) {
        NewTaskFlow newTaskFlow = newTaskFlowMapper.selectById(id);
        if (newTaskFlow == null) {
            throw new BusinessException("任务流程关系不存在，ID：" + id);
        }
        return NewTaskFlowDTO.fromEntity(newTaskFlow);
    }

    @Override
    public NewTaskFlowDTO getNewTaskFlowByTaskIdAndFlowId(Long taskId, Long flowId) {
        NewTaskFlow newTaskFlow = newTaskFlowMapper.selectByTaskIdAndFlowId(taskId, flowId);
        if (newTaskFlow == null) {
            throw new BusinessException("任务流程关系不存在，任务ID：" + taskId + "，流程ID：" + flowId);
        }
        return NewTaskFlowDTO.fromEntity(newTaskFlow);
    }

    @Override
    public List<NewTaskFlowDTO> getNewTaskFlowsByTaskId(Long taskId) {
        List<NewTaskFlow> newTaskFlows = newTaskFlowMapper.selectByTaskId(taskId);
        return newTaskFlows.stream()
                .map(NewTaskFlowDTO::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    public List<NewTaskFlowDTO> getNewTaskFlowsByFlowId(Long flowId) {
        List<NewTaskFlow> newTaskFlows = newTaskFlowMapper.selectByFlowId(flowId);
        return newTaskFlows.stream()
                .map(NewTaskFlowDTO::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public NewTaskFlowDTO createNewTaskFlow(CreateNewTaskFlowRequest request) {
        // 检查任务流程关系是否已存在
        NewTaskFlow existingTaskFlow = newTaskFlowMapper.selectByTaskIdAndFlowId(request.getTaskId(), request.getFlowId());
        if (existingTaskFlow != null) {
            throw new BusinessException("任务流程关系已存在，任务ID：" + request.getTaskId() + "，流程ID：" + request.getFlowId());
        }

        NewTaskFlow newTaskFlow = new NewTaskFlow();
        newTaskFlow.setTaskId(request.getTaskId());
        newTaskFlow.setFlowId(request.getFlowId());
        newTaskFlow.setAssignedAt(LocalDateTime.now());
        // 设置数据源ID
        newTaskFlow.setDataSourceId(request.getDataSourceId());
        // isDistributed和distributedAt默认空缺，不需要设置

        int result = newTaskFlowMapper.insert(newTaskFlow);
        if (result == 0) {
            throw new BusinessException("任务流程关系创建失败");
        }
        return NewTaskFlowDTO.fromEntity(newTaskFlow);
    }

    @Override
    @Transactional
    public NewTaskFlowDTO updateNewTaskFlow(Long id, CreateNewTaskFlowRequest request) {
        NewTaskFlow existingTaskFlow = newTaskFlowMapper.selectById(id);
        if (existingTaskFlow == null) {
            throw new BusinessException("任务流程关系不存在，无法更新");
        }

        // 检查新的任务ID和流程ID组合是否已被其他记录使用
        if (!existingTaskFlow.getTaskId().equals(request.getTaskId()) || !existingTaskFlow.getFlowId().equals(request.getFlowId())) {
            NewTaskFlow otherTaskFlow = newTaskFlowMapper.selectByTaskIdAndFlowId(request.getTaskId(), request.getFlowId());
            if (otherTaskFlow != null && !otherTaskFlow.getId().equals(id)) {
                throw new BusinessException("任务流程关系已存在，任务ID：" + request.getTaskId() + "，流程ID：" + request.getFlowId());
            }
        }

        existingTaskFlow.setTaskId(request.getTaskId());
        existingTaskFlow.setFlowId(request.getFlowId());
        // assignedAt不更新，保持原来的分配时间

        int result = newTaskFlowMapper.updateById(existingTaskFlow);
        if (result == 0) {
            throw new BusinessException("任务流程关系更新失败");
        }
        return NewTaskFlowDTO.fromEntity(existingTaskFlow);
    }

    @Override
    @Transactional
    public void deleteNewTaskFlow(Long id) {
        NewTaskFlow newTaskFlow = newTaskFlowMapper.selectById(id);
        if (newTaskFlow == null) {
            throw new BusinessException("任务流程关系不存在，无法删除");
        }
        int result = newTaskFlowMapper.deleteById(id);
        if (result == 0) {
            throw new BusinessException("任务流程关系删除失败");
        }
    }
    
    @Override
    @Transactional
    public int batchAssignTasksToFlow(Long dataSourceId, Long processId) {
        //log.info("=== 开始批量分配任务到流程 ===");
        //log.info("输入参数：dataSourceId = {}, processId = {}", dataSourceId, processId);
        
        // 参数验证
        if (dataSourceId == null) {
            //log.error("参数验证失败：dataSourceId 不能为空");
            throw new BusinessException("数据源ID不能为空");
        }
        if (processId == null) {
            //log.error("参数验证失败：processId 不能为空");
            throw new BusinessException("流程ID不能为空");
        }
        //log.info("参数验证通过");
        
        try {
            // 1. 查询指定数据源ID且未分配的任务
            //log.info("步骤1：开始查询未分配的任务");
            //log.info("步骤1.1：调用 newTaskService.getNewTasks(page=0, size=MAX, dataSourceId={}, isAssigned=0)", dataSourceId);
            
            List<NewTaskDTO> unassignedTasks;
            try {
                unassignedTasks = newTaskService.getNewTasks(0, Integer.MAX_VALUE, dataSourceId, 0);
                //log.info("步骤1.2：查询未分配任务完成，数量 = {}", unassignedTasks != null ? unassignedTasks.size() : 0);
                
                if (unassignedTasks != null && !unassignedTasks.isEmpty()) {
                    //log.info("步骤1.3：未分配任务详情:");
                    for (int i = 0; i < Math.min(unassignedTasks.size(), 10); i++) { // 只显示前10个
                        NewTaskDTO task = unassignedTasks.get(i);
                        //log.info("  任务{}: ID={}, 业务唯一ID={}, 数据源ID={}, 分配状态={}", 
                                //i+1, task.getId(), task.getBizUniqueId(), task.getDataSourceId(), task.getIsAssigned());
                    }
                    if (unassignedTasks.size() > 10) {
                        //log.info("  ... 还有 {} 个任务未显示", unassignedTasks.size() - 10);
                    }
                }
            } catch (Exception e) {
                //log.error("步骤1.2：查询未分配任务失败，错误信息: {}", e.getMessage(), e);
                throw e;
            }
            
            if (unassignedTasks == null || unassignedTasks.isEmpty()) {
                //log.info("步骤1.4：没有符合条件的未分配任务，流程结束");
                return 0; // 没有符合条件的任务
            }
            
            int successCount = 0;
            int failureCount = 0;
            
            // 2. 遍历任务，更新分配状态并创建任务流程关系
            //log.info("步骤2：开始遍历任务进行分配");
            for (int i = 0; i < unassignedTasks.size(); i++) {
                NewTaskDTO task = unassignedTasks.get(i);
                //log.info("步骤2.{}: 处理任务 - ID={}, 业务唯一ID={}", i+1, task.getId(), task.getBizUniqueId());
                
                try {
                    // 2.1 更新任务的分配状态为1（已分配）
                    //log.info("步骤2.{}.1: 更新任务分配状态为已分配", i+1);
                    try {
                        newTaskService.updateNewTaskAssignedStatus(task.getId(), 1);
                        //log.info("步骤2.{}.1: 任务分配状态更新成功", i+1);
                    } catch (Exception e) {
                        //log.error("步骤2.{}.1: 更新任务分配状态失败，错误信息: {}", i+1, e.getMessage(), e);
                        throw e;
                    }
                    
                    // 2.2 创建任务流程关系
                    //log.info("步骤2.{}.2: 创建任务流程关系", i+1);
                    CreateNewTaskFlowRequest flowRequest = new CreateNewTaskFlowRequest();
                    flowRequest.setTaskId(task.getId());
                    flowRequest.setFlowId(processId);
                    // 设置数据源ID
                    flowRequest.setDataSourceId(dataSourceId);
                    
                    //log.info("步骤2.{}.2: 任务流程关系请求参数 - TaskID={}, FlowID={}, DataSourceID={}", 
                            //i+1, flowRequest.getTaskId(), flowRequest.getFlowId(), flowRequest.getDataSourceId());
                    
                    // 尝试创建，如果已存在则跳过
                    try {
                        createNewTaskFlow(flowRequest);
                        successCount++;
                        //log.info("步骤2.{}.2: 任务流程关系创建成功，当前成功数量 = {}", i+1, successCount);
                    } catch (BusinessException e) {
                        if (e.getMessage().contains("任务流程关系已存在")) {
                            //log.warn("步骤2.{}.2: 任务流程关系已存在，跳过该任务", i+1);
                            // 关系已存在，继续处理下一个任务
                            continue;
                        }
                        // 其他异常重新抛出
                        //log.error("步骤2.{}.2: 创建任务流程关系失败，业务异常: {}", i+1, e.getMessage(), e);
                        throw e;
                    } catch (Exception e) {
                        //log.error("步骤2.{}.2: 创建任务流程关系失败，系统异常: {}", i+1, e.getMessage(), e);
                        throw e;
                    }
                } catch (Exception e) {
                    failureCount++;
                    //log.error("步骤2.{}: 分配任务到流程失败，任务ID：{}，流程ID：{}，错误：{}", 
                            //i+1, task.getId(), processId, e.getMessage(), e);
                    // 可以选择继续处理下一个任务或者抛出异常中断整个批次
                    // 这里选择继续处理下一个任务
                }
            }
            
            //log.info("=== 批量分配任务到流程完成 ===");
            //log.info("总任务数: {}, 成功分配: {}, 失败数量: {}", unassignedTasks.size(), successCount, failureCount);
            
            return successCount;
            
        } catch (Exception e) {
            //log.error("=== 批量分配任务到流程失败 ===");
            //log.error("异常类型: {}", e.getClass().getSimpleName());
            //log.error("异常信息: {}", e.getMessage());
            //log.error("异常堆栈:", e);
            throw e;
        }
    }

    @Override
    public List<NewTaskFlowDTO> getUndistributedTaskFlowsByDataSourceId(Long dataSourceId) {
        //log.info("查询指定数据源的未分发任务流程关系，dataSourceId = {}", dataSourceId);
        
        if (dataSourceId == null) {
            //log.error("参数验证失败：dataSourceId 不能为空");
            throw new BusinessException("数据源ID不能为空");
        }
        
        try {
            List<NewTaskFlow> undistributedTaskFlows = newTaskFlowMapper.selectUndistributedByDataSourceId(dataSourceId);
            //log.info("查询未分发任务流程关系完成，数量 = {}", undistributedTaskFlows != null ? undistributedTaskFlows.size() : 0);
            
            return undistributedTaskFlows.stream()
                    .map(NewTaskFlowDTO::fromEntity)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            //log.error("查询未分发任务流程关系失败，错误信息: {}", e.getMessage(), e);
            throw new BusinessException("查询未分发任务流程关系失败: " + e.getMessage());
        }
    }

    @Override
    public List<NewTaskFlowDTO> getUndistributedTaskFlowsByFlowId(Long flowId) {
        //log.info("根据流程ID查询未分发的任务流程关系，flowId = {}", flowId);
        
        if (flowId == null) {
            //log.error("参数验证失败：flowId 不能为空");
            throw new BusinessException("流程ID不能为空");
        }
        
        try {
            List<NewTaskFlow> undistributedTaskFlows = newTaskFlowMapper.selectUndistributedByFlowId(flowId);
            //log.info("查询未分发任务流程关系完成，数量 = {}", undistributedTaskFlows != null ? undistributedTaskFlows.size() : 0);
            
            return undistributedTaskFlows.stream()
                    .map(NewTaskFlowDTO::fromEntity)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            //log.error("查询未分发任务流程关系失败，错误信息: {}", e.getMessage(), e);
            throw new BusinessException("查询未分发任务流程关系失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public int batchDistributeTaskFlows(Long dataSourceId) {
        //log.info("=== 开始批量分发任务流程关系 ===\ndataSourceId = {}", dataSourceId);
        
        if (dataSourceId == null) {
            //log.error("参数验证失败：dataSourceId 不能为空");
            throw new BusinessException("数据源ID不能为空");
        }
        
        try {
            // 1. 查询指定数据源的未分发任务流程关系
            //log.info("步骤1：查询未分发的任务流程关系");
            List<NewTaskFlow> undistributedTaskFlows = newTaskFlowMapper.selectUndistributedByDataSourceId(dataSourceId);
            //log.info("步骤1：查询完成，未分发任务流程关系数量 = {}", undistributedTaskFlows != null ? undistributedTaskFlows.size() : 0);
            
            if (undistributedTaskFlows == null || undistributedTaskFlows.isEmpty()) {
                //log.info("没有符合条件的未分发任务流程关系，流程结束");
                return 0;
            }
            
            // 2. 提取ID列表
            List<Long> taskFlowIds = undistributedTaskFlows.stream()
                    .map(NewTaskFlow::getId)
                    .collect(Collectors.toList());
            //log.info("步骤2：提取任务流程关系ID列表，数量 = {}", taskFlowIds.size());
            
            // 3. 批量更新分发状态
            //log.info("步骤3：批量更新分发状态为已分发");
            int updateCount = newTaskFlowMapper.batchUpdateDistributedStatus(taskFlowIds, true);
            //log.info("步骤3：批量更新完成，更新数量 = {}", updateCount);
            
            // 4. 为每个任务流程关系创建审批状态记录
            //log.info("步骤4：开始创建审批状态记录");
            List<TaskApprovalStatus> approvalStatusList = new ArrayList<>();
            int totalApprovalRecords = 0;
            
            for (int i = 0; i < undistributedTaskFlows.size(); i++) {
                NewTaskFlow taskFlow = undistributedTaskFlows.get(i);
                //log.info("步骤4.{}: 处理任务流程关系 - ID={}, TaskID={}, FlowID={}, DataSourceID={}", 
                        //i+1, taskFlow.getId(), taskFlow.getTaskId(), taskFlow.getFlowId(), taskFlow.getDataSourceId());
                
                // 根据flowId查询ProcessNode表中的节点信息
                //log.info("步骤4.{}.1：根据flowId={}查询流程节点", i+1, taskFlow.getFlowId());
                List<ProcessNodeDTO> processNodes;
                try {
                    processNodes = processNodeService.getProcessNodes(taskFlow.getFlowId());
                    //log.info("步骤4.{}.2：查询流程节点完成，节点数量 = {}", i+1, processNodes != null ? processNodes.size() : 0);
                } catch (Exception e) {
                    //log.error("步骤4.{}.2：查询流程节点失败，错误信息: {}", i+1, e.getMessage(), e);
                    continue; // 跳过这个任务流程关系
                }
                
                if (processNodes == null || processNodes.isEmpty()) {
                    //log.warn("步骤4.{}.3：流程ID: {} 下没有配置节点，跳过", i+1, taskFlow.getFlowId());
                    continue;
                }
                
                // 为该任务流程关系的每个节点创建审批状态记录
                for (int j = 0; j < processNodes.size(); j++) {
                    ProcessNodeDTO node = processNodes.get(j);
                    totalApprovalRecords++;
                    //log.info("步骤4.{}.{}: 创建审批状态记录 - 任务流程ID={}, 节点ID={}, 节点名称={}, 节点顺序={}", 
                            //i+1, j+1, taskFlow.getId(), node.getId(), node.getNodeName(), node.getNodeOrder());
                    
                    TaskApprovalStatus approvalStatus = new TaskApprovalStatus();
                    approvalStatus.setTaskFlowId(taskFlow.getId());
                    approvalStatus.setNodeId(node.getId());
                    approvalStatus.setNodeOrder(node.getNodeOrder());
                    // 如果节点顺序为1，设置状态为1（正在处理），否则为0（待处理）
                    approvalStatus.setStatus(node.getNodeOrder() == 1 ? 1 : 0);
                    approvalStatus.setApproverId(null); // 处理人为空
                    approvalStatus.setApproverName(null); // 处理人姓名为空
                    approvalStatus.setComment(null);
                    approvalStatus.setStartTime(null);
                    approvalStatus.setEndTime(null);
                    approvalStatus.setTaskId(taskFlow.getTaskId());
                    approvalStatus.setDataSourceId(dataSourceId);
                    approvalStatus.setFlowId(taskFlow.getFlowId());
                     // 设置节点顺序
                    approvalStatus.setCreatedAt(LocalDateTime.now());
                    approvalStatus.setUpdatedAt(LocalDateTime.now());
                    
                    approvalStatusList.add(approvalStatus);
                    //log.debug("审批状态记录详情: TaskFlowID={}, NodeID={}, TaskID={}, DataSourceID={}, FlowID={}, NodeOrder={}", 
//                            approvalStatus.getTaskFlowId(), approvalStatus.getNodeId(),
//                            approvalStatus.getTaskId(), approvalStatus.getDataSourceId(),
//                            approvalStatus.getFlowId(), node.getNodeOrder());
                }
            }
            
            //log.info("步骤4.总结：共创建 {} 条审批状态记录", approvalStatusList.size());
            
            // 5. 批量插入审批状态记录
            if (!approvalStatusList.isEmpty()) {
                //log.info("步骤5：开始批量插入审批状态记录，数量 = {}", approvalStatusList.size());
                try {
                    int insertedCount = taskApprovalStatusMapper.batchInsert(approvalStatusList);
                    //log.info("步骤5.1：批量插入完成，实际插入数量 = {}", insertedCount);
                    
                    if (insertedCount != approvalStatusList.size()) {
                        //log.warn("步骤5.2：插入数量不匹配！期望插入 {} 条，实际插入 {} 条", approvalStatusList.size(), insertedCount);
                    }
                } catch (Exception e) {
                    //log.error("步骤5.1：批量插入审批状态记录失败，错误信息: {}", e.getMessage(), e);
                    throw e;
                }
            } else {
                //log.warn("步骤5：没有审批状态记录需要插入");
            }
            
            //log.info("=== 批量分发任务流程关系完成 ===\n总处理数: {}\n成功分发数: {}\n创建审批状态记录数: {}", 
                    //undistributedTaskFlows.size(), updateCount, approvalStatusList.size());
            return updateCount;
            
        } catch (Exception e) {
            //log.error("批量分发任务流程关系过程中发生异常，错误信息: {}", e.getMessage(), e);
            throw new BusinessException("批量分发任务流程关系失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public int batchDistributeTaskFlowsByFlowId(Long flowId) {
        //log.info("=== 开始根据流程ID批量分发任务流程关系 ===\nflowId = {}", flowId);
        
        if (flowId == null) {
            //log.error("参数验证失败：flowId 不能为空");
            throw new BusinessException("流程ID不能为空");
        }
        
        try {
            // 1. 查询指定流程的未分发任务流程关系
            //log.info("步骤1：查询未分发的任务流程关系");
            List<NewTaskFlow> undistributedTaskFlows = newTaskFlowMapper.selectUndistributedByFlowId(flowId);
            //log.info("步骤1：查询完成，未分发任务流程关系数量 = {}", undistributedTaskFlows != null ? undistributedTaskFlows.size() : 0);
            
            if (undistributedTaskFlows == null || undistributedTaskFlows.isEmpty()) {
                //log.info("没有符合条件的未分发任务流程关系，流程结束");
                return 0;
            }
            
            // 2. 提取ID列表
            List<Long> taskFlowIds = undistributedTaskFlows.stream()
                    .map(NewTaskFlow::getId)
                    .collect(Collectors.toList());
            //log.info("步骤2：提取任务流程关系ID列表，数量 = {}", taskFlowIds.size());
            
            // 3. 批量更新分发状态
            //log.info("步骤3：批量更新分发状态为已分发");
            int updateCount = newTaskFlowMapper.batchUpdateDistributedStatus(taskFlowIds, true);
            //log.info("步骤3：批量更新完成，更新数量 = {}", updateCount);
            
            // 4. 为每个任务流程关系创建审批状态记录
            //log.info("步骤4：开始创建审批状态记录");
            List<TaskApprovalStatus> approvalStatusList = new ArrayList<>();
            int totalApprovalRecords = 0;
            
            // 先查询流程节点信息（因为所有任务流程关系都是同一个flowId）
            //log.info("步骤4.1：根据flowId={}查询流程节点", flowId);
            List<ProcessNodeDTO> processNodes;
            try {
                processNodes = processNodeService.getProcessNodes(flowId);
                //log.info("步骤4.2：查询流程节点完成，节点数量 = {}", processNodes != null ? processNodes.size() : 0);
            } catch (Exception e) {
                //log.error("步骤4.2：查询流程节点失败，错误信息: {}", e.getMessage(), e);
                //log.info("=== 根据流程ID批量分发任务流程关系完成（无审批状态记录） ===\n总处理数: {}\n成功分发数: {}", undistributedTaskFlows.size(), updateCount);
                return updateCount;
            }
            
            if (processNodes == null || processNodes.isEmpty()) {
                //log.warn("步骤4.3：流程ID: {} 下没有配置节点，跳过审批状态记录创建", flowId);
                //log.info("=== 根据流程ID批量分发任务流程关系完成（无审批状态记录） ===\n总处理数: {}\n成功分发数: {}", undistributedTaskFlows.size(), updateCount);
                return updateCount;
            }
            
            // 为每个任务流程关系的每个节点创建审批状态记录
            for (int i = 0; i < undistributedTaskFlows.size(); i++) {
                NewTaskFlow taskFlow = undistributedTaskFlows.get(i);
                //log.info("步骤4.{}: 处理任务流程关系 - ID={}, TaskID={}, FlowID={}, DataSourceID={}", 
//                        i+1, taskFlow.getId(), taskFlow.getTaskId(), taskFlow.getFlowId(), taskFlow.getDataSourceId());
                
                for (int j = 0; j < processNodes.size(); j++) {
                    ProcessNodeDTO node = processNodes.get(j);
                    totalApprovalRecords++;
                    //log.info("步骤4.{}.{}: 创建审批状态记录 - 任务流程ID={}, 节点ID={}, 节点名称={}, 节点顺序={}", 
//                            i+1, j+1, taskFlow.getId(), node.getId(), node.getNodeName(), node.getNodeOrder());
                    
                    TaskApprovalStatus approvalStatus = new TaskApprovalStatus();
                     approvalStatus.setTaskFlowId(taskFlow.getId());
                     approvalStatus.setNodeId(node.getId());
                     // 如果节点顺序为1，设置状态为1（正在处理），否则为0（待处理）
                     approvalStatus.setStatus(node.getNodeOrder() == 1 ? 1 : 0);
                     approvalStatus.setApproverId(null); // 处理人为空
                     approvalStatus.setApproverName(null); // 处理人姓名为空
                     approvalStatus.setComment(null);
                     approvalStatus.setStartTime(null);
                     approvalStatus.setEndTime(null);
                     approvalStatus.setTaskId(taskFlow.getTaskId());
                     approvalStatus.setDataSourceId(taskFlow.getDataSourceId());
                     approvalStatus.setFlowId(taskFlow.getFlowId());
                     approvalStatus.setNodeOrder(node.getNodeOrder()); // 设置节点顺序
                     approvalStatus.setCreatedAt(LocalDateTime.now());
                     approvalStatus.setUpdatedAt(LocalDateTime.now());
                    
                    approvalStatusList.add(approvalStatus);
                }
            }
            
            //log.info("步骤4.总结：共创建 {} 条审批状态记录", approvalStatusList.size());
            
            // 5. 批量插入审批状态记录
            if (!approvalStatusList.isEmpty()) {
                //log.info("步骤5：开始批量插入审批状态记录，数量 = {}", approvalStatusList.size());
                try {
                    int insertedCount = taskApprovalStatusMapper.batchInsert(approvalStatusList);
                    //log.info("步骤5.1：批量插入完成，实际插入数量 = {}", insertedCount);
                    
                    if (insertedCount != approvalStatusList.size()) {
                        //log.warn("步骤5.2：插入数量不匹配！期望插入 {} 条，实际插入 {} 条", approvalStatusList.size(), insertedCount);
                    }
                } catch (Exception e) {
                    //log.error("步骤5.1：批量插入审批状态记录失败，错误信息: {}", e.getMessage(), e);
                    throw e;
                }
            } else {
                //log.warn("步骤5：没有审批状态记录需要插入");
            }
            
            //log.info("=== 根据流程ID批量分发任务流程关系完成 ===\n总处理数: {}\n成功分发数: {}\n创建审批状态记录数: {}", 
//                    undistributedTaskFlows.size(), updateCount, approvalStatusList.size());
            return updateCount;
            
        } catch (Exception e) {
            //log.error("根据流程ID批量分发任务流程关系过程中发生异常，错误信息: {}", e.getMessage(), e);
            throw new BusinessException("根据流程ID批量分发任务流程关系失败: " + e.getMessage());
        }
    }
}